<?php
/**
 * Created by PhpStorm.
 * User: chennan
 * Date: 2017/11/29
 * Time: 1:27
 */

namespace common\business\qywx;


use common\business\DbHandler;
use common\helpers\StringUtil;
use linslin\yii2\curl\Curl;
use yii\helpers\Json;

class QywxApiHandler extends DbHandler
{
    /**
     * @var string
     */
    protected $baseUrl = 'https://qyapi.weixin.qq.com/cgi-bin';
    /**
     * @var array
     */
    protected $_responseArr;

    /**
     * @param $url string
     * @param $params array
     * @param callback|null $writeBackHandler
     * @param bool $asArray
     * @return bool
     */
    protected function getJson($url, $params, $writeBackHandler = null, $asArray = false){
        $curl = new Curl();
        $curl->setOptions([
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => ["Content-type: application/json; charset=UTF-8"],
            CURLOPT_TIMEOUT        => 500,
        ]);
        $curl->setGetParams($params);
        $response = $curl->get($url);
        return $this->handleResponse($curl, $response, $writeBackHandler, $asArray);
    }

    /**
     * @param $url string
     * $param $params array
     * @param $body
     * @param callback|null $writeBackHandler
     * @param bool $asArray
     * @return bool
     */
    protected function postJson($url, $params, $body, $writeBackHandler = null, $asArray = false){
        $curl = new Curl();
        if (StringUtil::isNullOrWhiteSpace($body)) {
            $this->addError('Post Json', 'Content is null');
            if (isset($writeBackHandler)){
                $responseArr = ['errcode' => 1, 'errmsg' => 'Content is null'];
                call_user_func_array($writeBackHandler, $responseArr);
            }
            return false;
        }
        $curl->setOptions([
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => ["Content-type: application/json; charset=UTF-8"],
            CURLOPT_TIMEOUT        => 500,
        ]);
        $curl->setGetParams($params);
        $curl->setOption(
            CURLOPT_POSTFIELDS,
            $body
        );
        $response = $curl->post($url);
        return $this->handleResponse($curl, $response, $writeBackHandler, $asArray);
    }


    /**
     * @param $curl Curl
     * @param $response mixed|array
     * @param callback|null $writeBackHandler
     * @param bool $asArray
     * @return bool
     */
    protected function handleResponse($curl, $response, $writeBackHandler = null, $asArray = false){
        if ($curl->responseCode != 200){
            $exceptionStr = sprintf('responseCode: %s', $curl->responseCode);
            $responseArr = ['errcode' => $curl->responseCode, 'errmsg' => $exceptionStr];
            $this->addError('Response Code', $curl->responseCode);
            $isSuccess = false;
        }
        else {
            if ($curl->errorCode === null) {
//                {
//               "errcode": 0,
//               "errmsg": "deleted"
//                }
                if ($asArray){
                    $responseArr = ['response' => $response];
                }
                else {
                    $responseArr = Json::decode($response);
                }
                $isSuccess = true;
            } else {
                $exceptionStr = sprintf('errorCode: %s, errorText: %s', $curl->errorCode, $curl->errorText);
                $responseArr = ['errcode' => $curl->errorCode, 'errmsg' => $exceptionStr];
                $this->addError('Response', $exceptionStr);
                $isSuccess = false;
            }
        }
        if (isset($writeBackHandler)){
            call_user_func_array($writeBackHandler, $responseArr);
        }
        return $isSuccess;
    }
}